<?php

// 数据库配置
include 'config.php';

// 检查是否是 GET 请求
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    // 获取 GET 数据
    $lxqq = $_GET['lxqq'] ?? '';
    $qq = $_GET['qq'] ?? '';
    $kami = $_GET['kami'] ?? '';
    $now_time = time();

    // 检查卡密是否存在并且未被使用
    $checkStmt = $conn->prepare("SELECT * FROM kami WHERE kami = ? AND zt = 0");
    $checkStmt->bind_param("s", $kami);
    $checkStmt->execute();
    $result = $checkStmt->get_result();
    $row = $result->fetch_assoc();

    if ($row) {
        // 如果卡密存在且未被使用
        if (empty($row['qq'])) {
            // 如果是第一次授权
            $vip_time_duration = $row['type'] == 1 ? 2592000 : ($row['type'] == 2 ? 31536000 : 999999999999); // 月卡30天，年卡365天，永久卡0
            $vip_time = $now_time + $vip_time_duration;

            // 插入授权信息到 sq 表
            
            $insertStmt = $conn->prepare("INSERT INTO sq (qq, lxqq, now_time, vip_time, ty) VALUES (?, ?, ?, ?, ?)");
           $type = 2;
$insertStmt->bind_param("ssiii", $qq, $lxqq, $now_time, $vip_time, $type);
            if ($insertStmt->execute()) {
                // 更新卡密状态为已使用
               $updateKamiStmt = $conn->prepare("UPDATE kami SET zt = 1, qq = ? WHERE kami = ?");
            $updateKamiStmt->bind_param("ss", $qq, $kami);
                $updateKamiStmt->execute();

                $response = [
                    "code" => "200",
                    "msg" => "授权成功",
                    "now_time" => $now_time,
                    "vip_time" => $vip_time
                ];
            } else {
                $response = [
                    "code" => "500",
                    "msg" => "授权失败",
                    "error" => $insertStmt->error
                ];
            }
        } else {
            // 如果不是第一次授权，增加有效时长
            $new_vip_time = $now_time + ($row['type'] == 1 ? 2592000 : ($row['type'] == 2 ? 31536000 : 999999999999));
            $updateStmt = $conn->prepare("UPDATE sq SET vip_time = ? WHERE qq = ?");
            $updateStmt->bind_param("is", $new_vip_time, $qq);
            if ($updateStmt->execute()) {
                $response = [
                    "code" => "200",
                    "msg" => "授权时长更新成功",
                    "vip_time" => $new_vip_time
                ];
            } else {
                $response = [
                    "code" => "500",
                    "msg" => "授权时长更新失败",
                    "error" => $updateStmt->error
                ];
            }
        }
    } else {
        // 如果卡密不存在或已被使用
        $response = [
            "code" => "404",
            "msg" => "卡密不存在或已被使用"
        ];
    }

    // 返回 JSON 响应
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
} else {
    // 如果不是 GET 请求，返回错误
    header("HTTP/1.1 405 Method Not Allowed");
    exit("仅支持 GET 请求");
}

// 关闭数据库连接
$conn->close();
?>